//
//  uploadFileToHost.swift
//  股票框架
//
//  Created by 李小骥 on 2017/10/23.
//  Copyright © 2017年 李小骥. All rights reserved.
//

import Foundation
//分界标识
let boundaryStr="--"
let boundaryID="haha"
func uploadFileToHost(urlString:String,name:String,fileName:String,mimeType:String,paramters:String?,fileData:NSData, sucess :@escaping (NSData?)->Void, failure :@escaping (NSError?)->Void ){
    if urlString.isEmpty{
        print ("主地址不能为空")
        return
    }
    //固定拼接的第一部分
    let top=NSMutableString()
    top.appendFormat("%@%@\r\n", boundaryStr,boundaryID)
    top.appendFormat("Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name,fileName)
    top.appendFormat("Content-Type: %s\r\n\r\n", mimeType)
    //固定拼接第三部分
    let buttom=NSMutableString()
    buttom.appendFormat("%@%@\r\n", boundaryStr,boundaryID)
    buttom.append("Content-Disposition: form-data; name=\"submit\"\r\n\r\n")
    buttom.append("Submit\r\n")
    buttom.appendFormat("%@%@--\r\n", boundaryStr,boundaryID)
    //拼接
    let fromData=NSMutableData()
    //非文件参数
    if (paramters != nil){
        fromData.append((paramters?.data(using: String.Encoding.utf8))!)
    }
    fromData.append(top.data(using: String.Encoding.utf8.rawValue)!)
    fromData.append(fileData as Data)
    fromData.append(buttom.data(using: String.Encoding.utf8.rawValue)!)
    //可变请求
    let requset=NSMutableURLRequest(url: NSURL(string: urlString)! as URL)
    requset.httpBody=fromData as Data
    requset.httpMethod="POST"
    requset.addValue(String(fromData.length), forHTTPHeaderField:"Content-Length")
    let contype=String(format: "multipart/form-data; boundary=haha", boundaryID)
    requset.setValue(contype, forHTTPHeaderField: "Content-Type")
    let session=URLSession.shared
    session.uploadTask(with: requset as URLRequest, from: nil) { (responseData, response, error) -> Void in
        if error==nil{
            sucess(responseData! as NSData)
        }
        else{
            failure(error! as NSError)
        }
        }.resume()
}


